
import { getLocale } from '../../init/i18n'
import type {SortDistrict} from './tencentApi'

let mapKey = "AIzaSyB8_7OQOUR8AFE5MDFjv3DtFY-84E_ntAQ";

const gGetMapKey = () => mapKey

const requestReject = (reject: (p: { status: number }) => void) =>
	reject({ status: 500 });

type RequestParams = {
	url: string;
	data: Record<string, any>;
};
type RequestRes<T> = {
	results: Array<T>;
};

const Request = <T = any>({
	url,
	data
}: RequestParams) =>
	new Promise<Array<T>>((resolve, reject) => {
		let _language = getLocale() as string
		let language = _language
		if (_language === 'zh_CN') {
			language = 'zh-CN'
		} else if (_language === 'zh_HK') {
			language = 'zh-HK'
		} else if (_language === 'en_US') {
			language = 'en'
		}
		data['language'] = language
		uni.request({
			url,
			data,
			success: (res) => {
				if (res.statusCode == 200) {
					if (res.data && (res.data as RequestRes<T>).results) {
						resolve((res.data as RequestRes<T>).results);
					} else {
						console.error("请求错误", res);
						requestReject(reject);
					}
				} else {
					console.error("请求失败");
					requestReject(reject);
				}
			},
			fail: (err) => {
				console.log(err, url);
				requestReject(reject);
			},
		});
	})

// 逆地址解析
const gGeolocation = (latitude: number, longitude: number, isGeolocation = true): Promise<{
	address_component: {
		district: string
		city: string
		province: string
	}
	latitude: number
	longitude: number
	address?: string
}> =>
	new Promise((resolve, reject) => {
		let data = {
			key: mapKey,
			latlng: latitude + "," + longitude,
		};
		if (isGeolocation) {
			Request<{
				address_components: {
					long_name: string
				}[]
			}>({
				url: 'https://maps.googleapis.com/maps/api/geocode/json',
				data
			})
				.then(res => {
					if (res[0]) {
						let [district, city, province] = res[0].address_components
						let _data = {
							address_component: {
								district: district?.long_name,
								city: city?.long_name || district?.long_name,
								province: province?.long_name
							},
							latitude,
							longitude
						}
						uni.setStorageSync('userGeolocation', _data)
						resolve(_data)
					} else {
						requestReject(reject);
					}

				})
				.catch(() => {
					let _data = {
						address_component: {
							district: '',
							city: '',
							province: ''
						},
						latitude,
						longitude,
						address: ''
					}
					uni.setStorageSync('userGeolocation', _data)
					resolve(_data)
				})
		} else {
			let _data = {
				address_component: {
					district: '',
					city: '',
					province: ''
				},
				latitude,
				longitude,
				address: ''
			}
			uni.setStorageSync('userGeolocation', _data)
			resolve(_data)
		}

	});
const gLoadMapScript = (arr: string[]) => {
	// if (arr?.length > 0) {
	// 	keyArr = arr
	// 	mapKey = keyArr[0]
	// 	mapKeyIndex = 0
	// }
}
// 根据地址信息转换经纬度
const gAddressToLocation = (address: string):Promise<{
    longitude: number;
    latitude: number;
}> => {
	return new Promise((resolve, reject) => {
		let data = {
			key: mapKey,
			address
		}
		Request<{
			geometry: {
				location: {
					lng: number,
					lat: number
				}
			}
		}>({
			url: 'https://maps.googleapis.com/maps/api/geocode/json',
			data
		})
			.then(res => {
				resolve({
					longitude: res[0].geometry.location.lng,
					latitude: res[0].geometry.location.lat,
				})
			})
			.catch(err => reject(err))
	})
}
type NearbyAddressParams = {
	latitude: number,
	longitude: number,
	keyword?: string
}
type AddressItem = {
	name: string,
	vicinity: string,
	formatted_address: string
	geometry: {
		location: {
			latitude: number,
			longitude: number
		}
	}
}
// 获取附近的可用地点
const gNearbyAddress = async ({
	latitude, longitude,
	keyword
}: NearbyAddressParams) => {
	let data: {
		key: string,
		location: string,
		radius: number,
		keyword?: string
	} = {
		key: mapKey,
		location: `${latitude},${longitude}`,
		radius: 1500
	}
	if (keyword) {
		data['keyword'] = keyword
	}
	const res = await Request<
		AddressItem>({
			url: 'https://maps.googleapis.com/maps/api/place/nearbysearch/json',
			data
		})
	return res.map(item => {
		return {
			...item,
			address:"",
			title:item.name,
			location: {
				lat: item.geometry.location.latitude,
				lng:  item.geometry.location.longitude
			}
		}
	})
}


const gGetDistrict = async ():Promise<Array<SortDistrict>> => { return [] }

// 搜索地址
const gSearchAddress = async ({
	latitude,
	longitude,
	keyword
}: {
	latitude: number,
	longitude: number,
	keyword?: string,
}) => {
	let data: Record<string, string | number | null> = {
		key: mapKey,
	}
	if (keyword) {
		data['query'] = keyword
	}
	if (latitude) {
		data['location'] = `${latitude},${longitude}`
	}
	const res = await Request<AddressItem>({
		url: 'https://maps.googleapis.com/maps/api/place/textsearch/json',
		data
	})
	if (res?.length) {
		return res.map(item => {
			return {
				...item,
				address:"",
				title:item.name,
				vicinity: item.formatted_address,
				location: {
					lat: item.geometry.location.latitude,
					lng:  item.geometry.location.longitude
				}
			}
		})
	}
	return []
}

export {
	gGetMapKey,
	gLoadMapScript,
	gGeolocation,
	gAddressToLocation,
	gNearbyAddress,
	gGetDistrict,
	gSearchAddress
}
